lunoquests = {}

--local buscape_speaknumber = 1

local buscape_speaksteps = {
	{
		speak = "Ola PLAYERNAME! Pena que voce nao esta nem no nivel 2. Assim eu poderia te contratar em minha fazenda.",
		bottontype = "close",
		method = nil
	},
	----------------------------------------------------------------------------------------------
	{
		speak = "Ola PLAYERNAME! Sou um fazendeiro que me mudei para ca a pouco tempo. Me chamo Buscape.",
		bottontype = "next",
		method = nil
	},
	{
		speak = "Eu estou oferecendo um emprego na fazenda para voce. Basta voce me trazer 48 sementes de trigo. Aceita me ajudar?",
		bottontype = "close",
		method = nil
	},
	----------------------------------------------------------------------------------------------
	{
		speak = "Voce ainda nao conseguiu os 48 sementes de trigos que eu pedi, PLAYERNAME.",
		bottontype = "close",
		method = nil
	},
	----------------------------------------------------------------------------------------------
	{
		speak = "Opa! Obrigado PLAYERNAME! Isso ajuda bastante!",
		bottontype = "next",
		method = nil
	},
	{
		speak = "Tome estes 10 paes como agradecimento!!",
		bottontype = "close",
		--method = nil
		
		method = function(self, player)
			--local player = minetest.get_player_by_name(self.speakwith)
			local itemWielded = player:get_wielded_item()
			itemWielded:take_item(48)
			player:set_wielded_item(itemWielded)
			
			player:get_inventory():add_item("main", ItemStack("farming:bread 10"))
			lunomods.givePercentXP(player, 50, 2) --aumenta 10% de XP do nivel atual
			local playername = player:get_player_name()
			lunomods.setCharValue(playername, "quest_buscape", 1)
			return itemWielded
		end
		--[[ ]]--
	},
	----------------------------------------------------------------------------------------------
	{
		speak = "Obrigado pela ajuda que voce me deu, PLAYERNAME!",
		bottontype = "close",
		method = nil
	}
}

--print("buscape_speaksteps="..dump(buscape_speaksteps))

--[[ ]]--


lunomobs:register_mob("lunoquests:buscape", {
	type = "npc",
	--random_names = {"Buscape"},
	selected_name = "Buscape",
	hp_max = 60, --Padrão = 4
	visual = "mesh",
	mesh="mobs_humanoid.b3d",
	textures = {"npc_fazendeiro_pai.png"},
	collisionbox = {-0.3,-1.0,-0.3, 0.3,0.8,0.3},
	visual_size= {x=1, y=1},
	makes_footstep_sound = true, --Faz som quando andas.
	view_range = 5,
	walk_percent = 50,  --Probabilidade dele ficar andando. Varia de 0 ~ 100% do tempo
	walk_velocity = 1,
	--run_velocity = 1,
	jump = false, --Comerciantes nao pulam!
	drops = { 
		--{name="lunomobs:coin", chance = 1, min=1, max=10,}, --Probabilidade é de 1:35 de cair entre 1 a 3 "minemoedas"
		--{name="lunomobs:trader1", chance = 1, min=1, max=1 ,},	--Probabilidade é de 1:20 (5%) de cair entre 1 a 3 "punhados de ouro"
	},
	light_resistant = true,
	armor = 100,
	drawtype = "front", -- se o mesh fo idesenha do de lado(size) ou de frante
	water_damage = 1, --1=Morte lenta
	lava_damage = 10,
	light_damage = 0,
	--attack_type = "dogfight",
	animation = {
		speed_normal=15, 
		stand_start=0, stand_end=79,
		walk_start=168, walk_end=187,
	},
	speakwith = "",
	fala_atual = 1,
	sounds={ random="mobs_human_male_hello", },
	--follow = "lunomobs:minecoin",
	--FONTE: https://github.com/PilzAdam/mobs/wiki/API
	on_rightclick = function(self, user)
		if user~=nil and user:is_player() then
			minetest.sound_play("mobs_human_male_hello", {pos=self.pos, max_hear_distance = self.view_range}) --toca som "mobs_sheep".ogg a distancia de 5 blocos do usuário.
			local playername = user:get_player_name()

			if minetest.check_player_privs(playername, {server=true}) and  user:get_player_control().aux1 then
				--O Admin pode reiniciar a quest segurando botao de correr e clicando com segundo botão do mouse sebre o NPC
				minetest.sound_play("sfx_falha", {object=user, max_hear_distance = 0})
				minetest.chat_send_player(playername,"NPC Buscape reiniciado para o GM '"..playername.."'!")
				lunomods.setCharValue(playername, "quest_buscape", 0) 
			end

			local quest_buscape = lunomods.getQuestStep(playername, "quest_buscape")
			print("quest_buscape="..quest_buscape)
			
			if quest_buscape == 0 then
				--buscape_speaknumber = 1
				local level = lunomods.getLevel(playername) 
				--print("level="..level)
				local itemWielded = user:get_wielded_item()
				--print("itemWielded="..dump(itemWielded))
				local itemname = itemWielded:get_name()
				--print("itemname='"..itemname.."'")
				
				if level < 2 then
					lunomobs:buscape_speak(self, user, 1)	
				elseif itemname~="farming:seed_wheat" then
					lunomobs:buscape_speak(self, user, 2)
				elseif itemname=="farming:seed_wheat" then
					local itemquantia = itemWielded:get_count()
					if itemquantia < 48 then
						lunomobs:buscape_speak(self, user, 4)
					else
						lunomobs:buscape_speak(self, user, 5)					
					end
				end
			else
				lunomobs:buscape_speak(self, user, 7)					
			end
			
			
			minetest.register_on_player_receive_fields(function(sender, formname, fields)
				--print("formname='"..formname.."'")
				if formname == "buscape_formspec" then
					print("fields="..dump(fields))
					if not fields.quit then
						--print("self.fala_atual="..dump(self.fala_atual))
						--lunomobs:buscape_speak(self, sender, buscape_speaknumber + 1)	
						self.fala_atual = self.fala_atual + 1
						lunomobs:buscape_speak(self, sender, self.fala_atual)	
					else
						self.doCallMob(self, sender, false)
					end
					return true
				end
			end)
			--[[ ]]--
			--self.doCallMob(self, sender, false) --Caso o usuário aperte ESC ante do fim da fala.
		end
	end,
})


function lunomobs:buscape_speak(self, sender, fala_id)
	local playername = sender:get_player_name()
	self.speakwith = playername

	--[[
	if self.selected_name == nil or self.selected_name == "" then  
		self.selected_name = self.random_names[math.random(1, #self.random_names)] 
	end
	]]--
	if self.owner == nil or self.owner == "" then 
		self.owner = sender:get_player_name() 
	end

	--if self.fala_atual == nil or self.fala_atual <= 0 then self.fala_atual = 1 end
	--minetest.chat_send_player(name,"fala_id='"..fala_id.."'")
	if fala_id == nil or fala_id <= 0 then fala_id = 1 end
	print("fala_id="..fala_id)
	self.fala_atual = fala_id
	print("self.fala_atual="..dump(self.fala_atual))
	--buscape_speaknumber = fala_id
	--print("self="..dump(self))
	
	if fala_id <= #buscape_speaksteps then
	
		self.doCallMob(self, sender, true)
	
	
		--print("buscape_speaksteps="..dump(buscape_speaksteps))
		--print("self="..dump(self))
		--print("self.buscape_speaksteps="..dump(self.buscape_speaksteps))
		--print("buscape_speaksteps="..dump(buscape_speaksteps))
		print("buscape_speaksteps[fala_id].speak="..dump(buscape_speaksteps[fala_id].speak))
	
		local buscape_formspec = 
		"size[8,3]"
		--.."label[0.5,0;"..self.trader_inventory.random_names[1]..":]"
		.."textarea[0.25,0.25;8,2.5;txtArea;Buscape diz:;"..lunomobs:buscape_strings(sender, buscape_speaksteps[fala_id].speak).."]"
	
		print("buscape_speaksteps[fala_id].bottontype="..dump(buscape_speaksteps[fala_id].bottontype))
		if buscape_speaksteps[fala_id].bottontype=="next" then
			buscape_formspec = buscape_formspec .. "button[3,2.5;2,0.75;next;Avancar]"
		elseif buscape_speaksteps[fala_id].bottontype=="close" then
			buscape_formspec = buscape_formspec .. "button_exit[3,2.5;2,0.75;closer;Fechar]"
			self.doCallMob(self, sender, false)
		end

		minetest.show_formspec(sender:get_player_name(),"buscape_formspec",buscape_formspec)
	
		if type(buscape_speaksteps[fala_id].method)=="function" then
			buscape_speaksteps[fala_id].method(self, sender)
		end
		--[[ ]]--
	end
end

function lunomobs:buscape_strings(player, text)
	local playername = player:get_player_name()
	text = text:gsub("PLAYERNAME", playername)
	return text
end

--[[
	lunomobs:register_spawn(
		name, 
		{nodes}, 
		max_light(0~20), min_light(0~20), chance(a cada x blocos de node), active_object_count(quantos spawn), max_height, spawn_func)
]]--
lunomobs:register_spawn(
	"lunoquests:buscape", --name, 
	{
		"farming:wheat_1", "farming:wheat_2", "farming:wheat_3", "farming:wheat_4", 
		"farming:wheat_5", "farming:wheat_6", "farming:wheat_7", "farming:wheat_8"
	}, 
	20, 		--max_light(0~20)
	-1, 		--min_light(0~20)
	7000, 	--chance(a cada x blocos de node)
	1, 		--active_object_count(quantos spawn)
	31000		--max_height
)


minetest.register_craftitem("lunoquests:buscape", {
	description = "Fazendeiro Buscape [NPC Quest]",
	groups = { mobs=1 },
	inventory_image = "obj_fazendeiro_pai.png",
	on_place = function(itemstack, placer, pointed_thing)
		if pointed_thing.above then
			local pos = pointed_thing.above
			pos.y = pos.y +1
			local myInstance = minetest.env:add_entity(pos, "lunoquests:buscape")
			local myNPC = myInstance:get_luaentity()
			myNPC.tamed = true
			--myNPC.selected_name = myTrade1.random_names[math.random(1, #myNPC.random_names)]
			--myNPC.textures = {"mobs_rat2.png"}
			myNPC.owner = placer:get_player_name()
			if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end
		end
		return itemstack
	end,
})

minetest.register_alias("buscape"				, "lunoquests:buscape")
minetest.register_alias("fazendeiro"			, "lunoquests:buscape")
minetest.register_alias("fazendeiropai"		, "lunoquests:buscape")

